package com.acme.concurrent.executor;


import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ProducerConsumer
 * <p/>
 * Producer and consumer tasks in a desktop search application
 *
 * @author Brian Goetz and Tim Peierls
 */
public class ProducerConsumer {

    private static final int N_CONSUMERS = Runtime.getRuntime().availableProcessors();

    public static void startIndexing(File[] roots) {

        FileFilter filter = new FileFilter() {
            public boolean accept(File file) {
                return true;
            }
        };

        final int MULTIPLIER = 2;

        FileQueuePool fileQueuePool = new FileQueuePool(N_CONSUMERS, roots.length);
        ExecutorService crawlerExecutor = Executors.newFixedThreadPool(10 * roots.length);
        ExecutorService indexerExecutor = Executors.newFixedThreadPool(N_CONSUMERS);


        for (File root : roots)
            crawlerExecutor.submit(new FileCrawler(fileQueuePool, filter, root, crawlerExecutor));

        for (int i = 0; i < N_CONSUMERS; i++)
            indexerExecutor.submit(new FileIndexer(fileQueuePool, i, indexerExecutor));



        try {
            fileQueuePool.awaitFinalization();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        fileQueuePool.shutdown();
        crawlerExecutor.shutdown();
        indexerExecutor.shutdown();
    }
}